<!-- 巡检计划 -->
<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="false">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">计划</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">巡检路线</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form1" label-position="right" label-width="100px" :rules="rules.rules1" :model="formData.data">
							<el-form-item label="巡检类型：" prop="inspectionType">
								<el-select class="zs-full-item" v-model="formData.data.inspectionType" :disabled="handleType == 'add' ? false : true">
									<el-option v-for="item in standradTypeList" :key="item.id" :label="item.dicName" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="路线名称：" prop="routeName">
								<el-input v-model="formData.data.routeName" :maxlength="50" :disabled="isReadOnly" />
							</el-form-item>
							<el-form-item label="选择角色：" prop="roleKey">
								<el-select class="zs-full-item" v-model="formData.data.roleKey" placeholder=" " filterable :disabled="isReadOnly">
									<el-option v-for="item in roleList" :key="item.role.roleKey" :label="item.role.name" :value="item.role.roleKey" />
								</el-select>
							</el-form-item>
							<el-form-item label="强制顺序：" prop="mandatorySequence">
								<el-select class="zs-full-item" v-model="formData.data.mandatorySequence" :disabled="isReadOnly">
									<el-option v-for="item in sortList" :key="item.id" :label="item.dicName" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="巡检时长：" prop="inspectionDuration">
								<div class="zs-layout-flex-row zs-layout-justify-between">
									<el-input class="date-num-input zs-space-right" v-model="formData.data.inspectionDuration" :maxlength="10" :disabled="isReadOnly" />
									<el-select style="width: 50%" class="zs-full-item" v-model="formData.data.unitOfInspectionDuration" :disabled="isReadOnly">
										<el-option v-for="item in unitList" :key="item.id" :label="item.dicName" :value="item.id" />
									</el-select>
								</div>
							</el-form-item>
							<el-form-item label="自动终止：" prop="autoEndType">
								<el-select class="zs-full-item" v-model="formData.data.autoEndType" :disabled="isReadOnly" @change="changeAutoEndType">
									<el-option label="是" :value="1" />
									<el-option label="否" :value="0" />
								</el-select>
							</el-form-item>
							<el-form-item v-if="formData.data.autoEndType == 1" label="超时时长：" prop="timeoutDuration">
								<div class="zs-layout-flex-row zs-layout-justify-between">
									<el-input class="date-num-input zs-space-right" v-model="formData.data.timeoutDuration" :maxlength="10" :disabled="isReadOnly" />
									<el-select style="width: 50%" class="zs-full-item" v-model="formData.data.unitOfTimeoutDuration" :disabled="isReadOnly">
										<el-option v-for="item in unitList" :key="item.id" :label="item.dicName" :value="item.id" />
									</el-select>
								</div>
							</el-form-item>
							<el-form-item label="说明：">
								<el-input v-model="formData.data.remark" :maxlength="curTextareaLength" show-word-limit type="textarea" :autosize="{ minRows: 2 }" :disabled="isReadOnly" />
							</el-form-item>
						</el-form>
					</div>
					<!-- card3 -->
					<EffectAndFailureTime ref="effectTimeRef" title="生效状态" id="effect-and-failure-time" :isReadOnly="isReadOnly" labelWidth="110px" />
					<!-- card4 -->
					<CreateUserInfo v-if="formData.data.id" ref="createDataRef" title="创建信息" id="create-user-info" />
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import EffectAndFailureTime from '@/components/effectAndFailureTime.vue';
	import CreateUserInfo from '@/components/createUserInfo.vue';
	import { planAddApi, planUpdateApi, planInfoApi } from '@/api/inspect.js';
	import { roleListApi } from '@/api/common.js';
	import { ElMessage } from 'element-plus';
	import { ref, reactive, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';

	const route = useRoute();

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
		standradTypeList: { type: Array },
		sortList: { type: Array },
	});

	let store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);
	const curTextareaLength = ref(store.state.uiTextareaLength);

	const unitList = [
		{ id: 3, dicName: '分钟' },
		{ id: 0, dicName: '小时' },
		{ id: 1, dicName: '天' },
	];

	const emit = defineEmits(['close']);

	let isShowDrawer = ref(props.isShow);

	let formData = reactive({ data: { mandatorySequence: 7, unitOfInspectionDuration: 0, inspectionDuration: 2, autoEndType:0, unitOfTimeoutDuration: 0, timeoutDuration:2,  } });

	const rules = reactive({
		rules1: {
			inspectionType: [{ required: true, message: '请选择巡检类型', trigger: 'change' }],
			routeName: [{ required: true, message: '请输入路线名称', trigger: ['blur', 'change'] }],
			roleKey: [{ required: true, message: '请选择角色', trigger: 'change' }],
			mandatorySequence: [{ required: true, message: '请选择强制顺序', trigger: 'change' }],
			autoEndType: [{ required: true, message: '请选择自动终止', trigger: '' }],
			inspectionDuration: [
				{ required: true, message: '请输入巡检时长', trigger: ['blur', 'change'] },
				{ pattern: /^\d+$/, message: '支持自然数' },
			],
			timeoutDuration: [
				{ required: true, message: '请输入超时时长', trigger: ['blur', 'change'] },
				{ pattern: /^\d+$/, message: '支持自然数' },
			],
		},
	});

	const curNodeList = ref([
		{ name: '巡检路线', id: 'sm-drawer-demo-card-01' },
		{ name: '生效状态', id: 'effect-and-failure-time' },
	]);

	const form1 = ref();
	const forms = [form1];
	let effectTimeRef = ref();
	let createDataRef = ref();

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && props.handleType == 'add' && initForm();
				newVal && ['info', 'edit'].includes(props.handleType) && getInfo(props.currentRow?.id);
			});
		},
	);

	//详情
	const getInfo = async id => {
		let res = await planInfoApi(id);
		if (res.data.code !== 200) return;
		let existCreate = curNodeList.value.find(item => item.id === 'create-user-info');
		!existCreate && curNodeList.value.push({ name: '创建信息', id: 'create-user-info' });
		formData.data = Object.assign(res.data.data);
		effectTimeRef.value.setTime({ effectTime: formData.data.startTime, expireTime: formData.data.endTime });
		nextTick(() => {
			createDataRef.value.setData(formData.data);
		});
	};

	//提交
	const doConfirm = async () => {
		const validatePromises = forms.map(form => new Promise(resolve => form.value.validate(resolve)));
		const timeModel = effectTimeRef.value.checkRequired();
		validatePromises.push(timeModel);

		Promise.all(validatePromises).then(async results => {
			const isValid = results.every(valid => valid);
			if (!isValid) return;
			let params = Object.assign(formData.data, effectTimeRef.value.getFiled());
			params.projectCode = route.query.projectCode;

			let res = formData.data.id ? await planUpdateApi(params) : await planAddApi(params);
			if (res.data.code == 200) {
				ElMessage({
					message: '提交成功',
					type: 'success',
				});
				isShowDrawer.value = false;
				emit('close', { isShow: false, isRefresh: true });
			}
		});
	};

	//关闭抽屉
	const handleClose = done => {
		effectTimeRef.value.restTime();
		emit('close', { isShow: false });
		done();
	};

	//改变自动终止开关
	const changeAutoEndType = (val) => {
		formData.data.unitOfTimeoutDuration = val == 1 ? 0 : ""
		formData.data.timeoutDuration = val == 1 ? 2 : ""
	}

	//表单初始化
	const initForm = () => {
		formData.data = { mandatorySequence: 7, unitOfInspectionDuration: 0, inspectionDuration: 2, autoEndType:0 };
		effectTimeRef.value.setTime({});
		forms.forEach(form => {
			form.value.resetFields();
		});
		let existCreate = curNodeList.value.find(item => item.id === 'create-user-info');
		existCreate && curNodeList.value.pop();
	};

	//角色列表
	let roleList = ref([]);
	const getRoleList = async () => {
		let res = await roleListApi();
		roleList.value = res.data.data || [];
	};

	getRoleList();
</script>
